<template>
  <view class="container">
    <!-- 健康指标快速录入 -->
    <view class="quick-form">
      <!-- <view class="section-title">健康数据录入</view> -->
      <uni-forms :modelValue="healthForm" label-width="80">
        <uni-forms-item label="鹅只编号" required>
          <uni-easyinput v-model="healthForm.gooseId" placeholder="输入鹅只编号"/>
        </uni-forms-item>
        
        <view class="form-row">
          <uni-forms-item label="体温(℃)" class="half-item">
            <uni-easyinput type="number" v-model="healthForm.temperature" 
              placeholder="39.0"/>
          </uni-forms-item>
          
          <uni-forms-item label="体重(kg)" class="half-item">
            <uni-easyinput type="number" v-model="healthForm.weight" 
              placeholder="5.2"/>
          </uni-forms-item>
        </view>

        <uni-forms-item label="健康状况">
          <uni-data-checkbox v-model="healthForm.healthStatus"
            :localdata="healthOptions"
          />
        </uni-forms-item>

        <uni-forms-item label="症状描述">
          <uni-easyinput type="textarea" v-model="healthForm.symptoms" 
            placeholder="输入观察到的症状"/>
        </uni-forms-item>

        <uni-forms-item label="处理措施">
          <uni-data-select v-model="healthForm.treatment" 
            :localdata="treatmentOptions"
            placeholder="选择处理措施"
          />
        </uni-forms-item>

        <view class="form-buttons">
          <button type="primary" @click="submitHealthData">提交记录</button>
          <button @click="resetForm">重置</button>
        </view>
      </uni-forms>
    </view>

    <!-- 健康状态看板 -->
    <view class="dashboard">
      <view class="stats-row">
        <view class="stat-card warning">
          <text class="stat-value">{{ abnormalCount }}</text>
          <text class="stat-label">异常个体</text>
        </view>
        <view class="stat-card success">
          <text class="stat-value">{{ normalPercentage }}%</text>
          <text class="stat-label">健康率</text>
        </view>
        <view class="stat-card info">
          <text class="stat-value">{{ lastVaccine }}</text>
          <text class="stat-label">最近疫苗</text>
        </view>
      </view>
    </view>

    <!-- 健康记录列表 -->
    <view class="record-section">
      <view class="section-header">
        <text class="section-title">健康记录</text>
        <uni-datetime-picker type="daterange" 
          v-model="dateRange"
          @change="filterByDate"
        />
      </view>

      <scroll-view scroll-y class="record-list">
        <view v-for="(item, index) in filteredRecords" :key="item.id" 
          class="record-item" :class="{ 'abnormal': item.status === '异常' }">
          <view class="item-header">
            <text class="goose-id">#{{ item.gooseId }}</text>
            <uni-tag :text="item.status" 
              :type="item.status === '正常' ? 'success' : 'error'"
              size="small"
            />
          </view>
          
          <view class="item-body">
            <view class="data-item">
              <uni-icons type="thermometer" size="16" color="#666"/>
              <text>{{ item.temperature }}℃</text>
            </view>
            
            <view class="data-item">
              <uni-icons type="eye" size="16" color="#666"/>
              <text class="symptoms">{{ item.symptoms || '无异常症状' }}</text>
            </view>
            
            <view class="data-item" v-if="item.treatment">
              <uni-icons type="first-aid-kit" size="16" color="#666"/>
              <text>{{ item.treatment }}</text>
            </view>
          </view>
          
          <view class="item-footer">
            <text class="record-time">{{ formatTime(item.timestamp) }}</text>
            <view class="actions">
              <uni-icons type="compose" size="18" @click="editRecord(index)"/>
              <uni-icons type="trash" size="18" @click="deleteRecord(item.id)"/>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

const healthForm = reactive({
  gooseId: '',
  temperature: null,
  weight: null,
  healthStatus: '正常',
  symptoms: '',
  treatment: ''
});

const healthRecords = ref([]);
const dateRange = ref([]);

// 选项配置
const healthOptions = ref([
  { value: '正常', text: '正常' },
  { value: '异常', text: '异常' },
  { value: '观察中', text: '观察中' }
]);

const treatmentOptions = ref([
  { value: '疫苗接种', text: '疫苗接种' },
  { value: '药物治疗', text: '药物治疗' },
  { value: '隔离观察', text: '隔离观察' },
  { value: '环境调整', text: '环境调整' }
]);

// 计算属性
const abnormalCount = computed(() => 
  healthRecords.value.filter(r => r.status !== '正常').length
);

const normalPercentage = computed(() => {
  const total = healthRecords.value.length;
  const normal = healthRecords.value.filter(r => r.status === '正常').length;
  return total ? Math.round((normal / total) * 100) : 0;
});

const lastVaccine = computed(() => {
  const vaccineRecord = healthRecords.value
    .reverse()
    .find(r => r.treatment === '疫苗接种');
  return vaccineRecord ? formatTime(vaccineRecord.timestamp) : '无记录';
});

// 数据过滤
const filteredRecords = computed(() => {
  return healthRecords.value.filter(record => {
    const [start, end] = dateRange.value;
    if (!start || !end) return true;
    return record.timestamp >= start && record.timestamp <= end;
  });
});

// 表单提交
const submitHealthData = () => {
  if (!validateForm()) return;
  
  const record = {
    id: Date.now(),
    timestamp: new Date().getTime(),
    ...healthForm
  };
  
  healthRecords.value.unshift(record);
  resetForm();
  uni.showToast({ title: '记录已保存' });
};

// 表单验证
const validateForm = () => {
  if (!healthForm.gooseId) {
    uni.showToast({ title: '请填写鹅只编号', icon: 'none' });
    return false;
  }
  return true;
};

// 重置表单
const resetForm = () => {
  Object.assign(healthForm, {
    gooseId: '',
    temperature: null,
    weight: null,
    healthStatus: '正常',
    symptoms: '',
    treatment: ''
  });
};

// 时间格式化
const formatTime = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} 
    ${pad(date.getHours())}:${pad(date.getMinutes())}`;
};

const pad = (n) => n.toString().padStart(2, '0');

// 初始化示例数据
onLoad(() => {
  healthRecords.value = [
    {
      id: 1,
      gooseId: 'GS0023',
      temperature: 40.2,
      weight: 4.8,
      healthStatus: '异常',
      symptoms: '食欲不振，羽毛蓬松',
      treatment: '隔离观察',
      timestamp: new Date('2024-03-10').getTime()
    }
  ];
});
</script>

<style scoped lang="scss">
.container {
  padding: 20rpx;
}

.quick-form {
  background: #fff;
  padding: 30rpx;
  border-radius: 12rpx;
  margin-bottom: 30rpx;
  
  .form-row {
    display: flex;
    gap: 20rpx;
    
    .half-item {
      flex: 1;
    }
  }
  
  .form-buttons {
    display: flex;
    gap: 20rpx;
    margin-top: 30rpx;
    
    button {
      flex: 1;
    }
  }
}

.dashboard {
  margin: 30rpx 0;
  
  .stats-row {
    display: flex;
    justify-content: space-between;
    gap: 20rpx;
    
    .stat-card {
      flex: 1;
      padding: 10rpx;
      border-radius: 12rpx;
      text-align: center;
      
      &.warning { background: #fff3e0; }
      &.success { background: #e8f5e9; }
      &.info { background: #e3f2fd; }
      
      .stat-value {
        display: block;
        font-size: 36rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }
      
      .stat-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.record-section {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8rpx;
  }
}

.record-list {
  max-height: 800rpx;
}

.record-item {
  background: #fff;
  padding: 30rpx;
  margin-bottom: 8rpx;
  border-radius: 12rpx;
  border-left: 8rpx solid #4CAF50;
  
  &.abnormal {
    border-left-color: #F44336;
  }
  
  .item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    
    .goose-id {
      font-weight: bold;
      color: #333;
    }
  }
  
  .item-body {
    .data-item {
      display: flex;
      align-items: center;
      gap: 10rpx;
      margin: 15rpx 0;
      color: #666;
      
      .symptoms {
        color: #F44336;
      }
    }
  }
  
  .item-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20rpx;
    font-size: 24rpx;
    color: #999;
    
    .actions {
      display: flex;
      gap: 30rpx;
      
      uni-icons {
        padding: 10rpx;
      }
    }
  }
}
</style>